package cn.edu.abtu.service.impl;

import cn.edu.abtu.client.VodClient;
import cn.edu.abtu.dao.*;
import cn.edu.abtu.entity.*;
import cn.edu.abtu.entity.chapter.ChapterVo;
import cn.edu.abtu.entity.frontvo.CourseFrontVo;
import cn.edu.abtu.entity.frontvo.CourseWebVo;
import cn.edu.abtu.entity.vo.CourseInfoVo;
import cn.edu.abtu.entity.vo.CoursePublishVo;
import cn.edu.abtu.exceptionhandler.GuliException;
import cn.edu.abtu.service.EduChapterService;
import cn.edu.abtu.service.EduCourseService;
import cn.edu.abtu.vo.ResponseData;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class EduCourseServiceImpl implements EduCourseService {

    @Autowired
    private EduCourseDao eduCourseDao;

    @Autowired
    private EduVideoDao eduVideoDao;

    @Autowired
    private EduChapterDao eduChapterDao;

    @Autowired
    private EduCourseDescriptionDao eduCourseDescriptionDao;

    @Autowired
    private CoursePublishVoDao coursePublishVoDao;

    @Autowired
    private VodClient vodClient;

    @Autowired
    private EduChapterService eduChapterService;

    @Autowired
    private CourseWebVoDao courseWebVoDao;

    @Override
    public ResponseData addCourseInfo(CourseInfoVo courseInfoVo) {
        //1.向课程表添加课程基本信息
        EduCourse eduCourse = new EduCourse();
        eduCourse.setGmtCreate(new Date()); //创建时间
        eduCourse.setGmtModified(new Date()); //修改时间
        //将courseInfoVo中和eduCourse所需的数据进行传递
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int insert = eduCourseDao.insert(eduCourse);
        if ( insert>0 ){
            EduCourseDescription eduCourseDescription = new EduCourseDescription();
            eduCourseDescription.setId(eduCourse.getId()); // 将课程的ID赋值给描述的ID,作为一对一关联
            eduCourseDescription.setDescription(courseInfoVo.getDescription()); //课程描述信息
            eduCourseDescription.setGmtCreate(new Date()); //创建时间
            eduCourseDescription.setGmtModified(new Date()); //修改时间
            int insert1 = eduCourseDescriptionDao.insert(eduCourseDescription);
            return ResponseData.success("课程基本信息添加成功",eduCourse.getId());
        }else {
            return ResponseData.fail("添加课程信息失败",null);
        }
    }

    @Override
    @Transactional(isolation = Isolation.SERIALIZABLE)
    public ResponseData deleteCourse(String courseId) {
        EduCourse eduCourse = eduCourseDao.selectById(courseId);
        // 1. 根据课程ID删除小节
        // 1.1 根据courseId查询小节(video)表中视频ID
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",courseId);
        queryWrapper.select("video_source_id"); //指定查询video_source_id这个字段
        List<EduVideo> eduVideoList = eduVideoDao.selectList(queryWrapper);
        List<String> videoList = new ArrayList<>();
        for (EduVideo eduVideo : eduVideoList) {
            String videoSourceId = eduVideo.getVideoSourceId();
            if (videoSourceId!=null){
                videoList.add(videoSourceId);
            }
        }
        if (videoList.size()>0){
            System.out.println(videoList);
            vodClient.deleteBatch(videoList);
        }
        // 1.2通过courseId删除视频存储在数据库中的小节
        QueryWrapper<EduVideo> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("course_id",courseId);
        int videoDelete = eduVideoDao.delete(videoQueryWrapper); //删除对应得视频文件

        // 2. 根据课程ID删除章节
        QueryWrapper<EduChapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id",courseId);
        int chapterDelete = eduChapterDao.delete(chapterQueryWrapper);
        // 3. 根据课程ID删除描述
        int descriptionDelete = eduCourseDescriptionDao.deleteById(courseId);
        // 4.根据课程ID删除课程本身
        int courseDelete = eduCourseDao.deleteById(courseId);
        if (courseDelete>0){
            return ResponseData.success(eduCourse.getTitle()+"课程删除成功!",null);
        }else {
            return ResponseData.fail(eduCourse.getTitle()+"课程删除啊失败!",null);
        }
    }

    @Override
    public ResponseData getCourseInfo(String courseId) {
        //1.查询课程表的内容
        QueryWrapper courseQueryWrapper = new QueryWrapper();
        courseQueryWrapper.eq("id",courseId);
        EduCourse eduCourse = eduCourseDao.selectOne(courseQueryWrapper);
        if (eduCourse == null){
            throw new GuliException(20001,"课程基本信息不存在");
        }
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(eduCourse,courseInfoVo);
        //2.查询描述表的内容
        QueryWrapper courseDescriptionQueryWrapper = new QueryWrapper();
        courseDescriptionQueryWrapper.eq("id",courseId);
        EduCourseDescription eduCourseDescription = eduCourseDescriptionDao.selectOne(courseDescriptionQueryWrapper);
        if (eduCourseDescription == null){
            throw new GuliException(20001,"课程描述信息不存在");
        }
        BeanUtils.copyProperties(eduCourseDescription,courseInfoVo);
        return ResponseData.success(courseInfoVo);
    }

    @Override
    public ResponseData getCoursePublishInfo(String courseId) {
        CoursePublishVo coursePublishInfo = coursePublishVoDao.getCoursePublishInfo(courseId);
        if (coursePublishInfo == null){
            throw new GuliException(20001,"课程信息为空");
        }
        return ResponseData.success("课程信息查询成功",coursePublishInfo);
    }

    @Override
    public ResponseData getCoursePage(Integer pageNum, Integer pageSize, String courseName, String status) {
        Page pageInfo = new Page(pageNum, pageSize);
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        if (courseName!=null){
            queryWrapper.like("title",courseName);
        }
        if (status!=null){
            queryWrapper.like("status",status);
        }
        queryWrapper.orderByDesc("gmt_create");
        Page mapsPage = eduCourseDao.selectPage(pageInfo, queryWrapper);
        return ResponseData.success(mapsPage);
    }

    @Override
    public ResponseData getFrontCourseList(Integer page, Integer limit, CourseFrontVo courseFrontVo) {
        Page pageInfo = new Page(page, limit);
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(courseFrontVo.getSubjectParentId())){
            queryWrapper.eq("subject_parent_id",courseFrontVo.getSubjectParentId());
        }
        if (!StringUtils.isEmpty(courseFrontVo.getSubjectId())){
            queryWrapper.eq("subject_id",courseFrontVo.getSubjectId());
        }
        if (!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())){
            queryWrapper.orderByDesc("buy_count",courseFrontVo.getBuyCountSort());
        }
        if (!StringUtils.isEmpty(courseFrontVo.getGmtCreateSort())){
            queryWrapper.orderByDesc("gmt_create",courseFrontVo.getGmtCreateSort());
        }
        if (!StringUtils.isEmpty(courseFrontVo.getPriceSort())){
            queryWrapper.orderByDesc("price",courseFrontVo.getPriceSort());
        }
        Page mapsPage = eduCourseDao.selectPage(pageInfo, queryWrapper);
        List<EduCourse> records = mapsPage.getRecords();
        long current = mapsPage.getCurrent();
        long pages = mapsPage.getPages();
        long size = mapsPage.getSize();
        long total = mapsPage.getTotal();
        boolean hasNext = mapsPage.hasNext();
        boolean hasPrevious = mapsPage.hasPrevious();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("records",records);
        hashMap.put("current",current);
        hashMap.put("pages",pages);
        hashMap.put("size",size);
        hashMap.put("total",total);
        hashMap.put("hasNext",hasNext);
        hashMap.put("hasPrevious",hasPrevious);
        return ResponseData.success("查询成功",hashMap);
    }

    @Override
    public ResponseData getFrontCourseInfo(String courseId) {
        //通过courseId查询该课程的章节和小节
        ResponseData chapterVideo = eduChapterService.getChapterVideo(courseId);
        List<ChapterVo> chapterVideoList = (List<ChapterVo>) chapterVideo.getData();

        CourseWebVo courseWebVo = courseWebVoDao.getCourseWebVoList(courseId);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("chapterVideoList",chapterVideoList);
        hashMap.put("courseWebVo",courseWebVo);
        return ResponseData.success("成功",hashMap);
    }

    @Override
    public ResponseData updateCourseInfo(CourseInfoVo courseInfoVo) {
        //1.修改基本的课程信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int updateEduCourse = eduCourseDao.updateById(eduCourse);
        if (updateEduCourse == 0){
            throw new GuliException(20001,"修改课程基本信息失败");
        }
        //2.修改课程的描述信息
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        BeanUtils.copyProperties(courseInfoVo,eduCourseDescription);
        int updateCourseDescription = eduCourseDescriptionDao.updateById(eduCourseDescription);
        if (updateCourseDescription == 0){
            throw new GuliException(20001,"修改课程描述信息失败");
        }
        return ResponseData.success("修改成功",null);
    }

    @Override
    public ResponseData publishCourse(String courseId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",courseId);
        EduCourse Course = eduCourseDao.selectOne(queryWrapper);
        EduCourse eduCourse = new EduCourse();
        eduCourse.setId(courseId);
        eduCourse.setStatus("Normal");
        int update = eduCourseDao.updateById(eduCourse);
        if (update>0){
            return ResponseData.success(Course.getTitle()+"课程信息发布成功!",null);
        }else {
            return ResponseData.fail("课程发布失败!",null);
        }
    }
}
